package com.haiheng.module_main.mode

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.bean.AccessTokenBean
import com.haiheng.common.bean.BookInfoBean
import com.haiheng.common.bean.UserInfoBean
import com.haiheng.common.bean.UserReqeBean
import com.haiheng.common.bean.res.ISBNBookPage
import com.haiheng.common.bean.res.QueryBookResp
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.http.*
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.utils.SPUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/4/14 0014
 * @Version: 1.0
 */
class MainViewModel : BaseViewModel() {
    val userInfoBean = MutableLiveData<UserInfoBean>()
    val bookInfoBean = MutableLiveData<BookInfoBean>()
//    var listBooks = MutableLiveData<List<BookInfoBean>>().apply {
//        value = emptyList()
//    }


    var showMsg = MutableLiveData<String>()

    fun addMachine() {
        api {
            val request = HttpRequest(API.PATH.EDC_MACH)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                .setJsonObjec(RequestDataHelper.getAddMachineData())
            var response = postJson<HttpResponse>(request) {}
            showMsg.postValue("${response.toJson()}")
            if (response != null) {
                if (response.errorCode.equals("0")) {
                    LogUtils.d("添加设备成功 :" + response.toJson())
                } else {
                    LogWriter.e("添加设备失败 :" + response.toJson())
                }
            } else {
                if (response != null
                    && response.errorMsg != null
                    && response.errorMsg.contains("Unauthorized")
                ) {
                    getToken()
                }
                LogWriter.e("addMachine失败 ${response.toJson()}")
            }
        }
    }

    fun getToken() {
        api {
            val request = HttpRequest(API.PATH.CONNECT_TOKEN)
                .putHeader("content-type", "application/x-www-form-urlencoded")
                .putParam("client_secret", API.PARAM.CLIENT_SECRET)
                .putParam("grant_type", API.PARAM.GRANT_TYPE)
                .putParam("client_id", API.PARAM.CLIENT_ID)
            var response = post<AccessTokenBean>(request) {}
            if (response != null && response.access_token != null) {
                LogUtils.d("获取token成功，更新本地token:" + response.toJson())
//                accessToken.postValue("${response.type} ${response.accessToken}")
                SPUtils.getInstance()
                    .put(AppConstant.SP_TOKEN, "${response.token_type} ${response.access_token}")
//                KVDatabase.set(API.PARAM_HEADER_TOKEN,"Bearer ${response.accessToken}")
            } else {
                LogWriter.e("获取token失败 ${response.toJson()}")
            }
        }
    }

    fun reportStatus() {
        LogUtils.d("ReportService reportStatus  ${this.hashCode()}")
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val request = HttpRequest(API.PATH.EDC_MACH_STATUS)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .setJsonObjec(RequestDataHelper.getAddStatusData())
                var response = postJson<HttpResponse>(request)
                showMsg.postValue("${response.toJson()}")
                if (response != null) {
                    if (response.errorCode.equals("0")) {
                        LogUtils.d("上报状态成功 :" + response.toJson())
                        LogWriter.e("上报状态成功 :" + response.toJson())
                    } else {
                        LogWriter.e("上报状态失败 :" + response.toJson())
                    }
                } else {
                    if (response != null
                        && response.errorMsg != null
                        && response.errorMsg.contains("Unauthorized")
                    ) {
                        getToken()
                    }
                    LogWriter.e("上报状态失败 ${response.toJson()}")
                }
                val event = MsgEvent()
                event.code = MsgCode.MSG_REPORT_STATUS
                event.msg = "上报状态结果:${response.toJson()}"
                ApplicationViewModel.get().even.postValue(event)
                showMsg.postValue("上报状态结果:${response.toJson()}")
            } catch (ex: Exception) {
                showMsg.postValue("上报状态异常 ${ex.toString()}")
                val event = MsgEvent()
                event.code = MsgCode.MSG_REPORT_STATUS
                event.msg = "上报状态异常 ${ex.toString()}"
                ApplicationViewModel.get().even.postValue(event)
                LogWriter.e("上报状态异常 ${ex.toString()}")
            }
        }
    }


    fun queryBookInfo(bookSn: String) {
        //900347
        viewModelScope.launch {
            try {
                val request = HttpRequest(API.POST_PATH)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                    .setJsonObjec(RequestDataHelper.getQueryBookInfoData(bookSn))
                var response = postJson<QueryBookResp>(request)
                LogUtils.d("书籍查询结果：${response}")
                if (response != null && response.result != null) {
                    bookInfoBean.postValue(response.result!!)
                } else {
                    bookInfoBean.postValue(BookInfoBean())
                }
            } catch (ex: Exception) {
                showMsg.postValue("查询书籍异常：${ex}")
            }
        }
    }


    fun queryBookIsbn(isbn: String) {
        //900347
        viewModelScope.launch {
            try {
                val request = HttpRequest(API.OPERATION.QUERYBYISBN)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_ISBN)
                    .putPath("isbn",isbn)
                var booksPage =get<ISBNBookPage>(request)
                if (booksPage != null && booksPage.data !=  null && booksPage.data.size > 0){
                    var page = booksPage.data.get(0)
                  var b =  BookInfoBean()
                    b.isbn = isbn
                    b.bookTitle = page.nameBook
                    b.author = page.author
                    bookInfoBean.postValue(b)
                }else{
                    queryBookInfo(isbn)
                }
            } catch (ex: Exception) {
                showMsg.postValue("查询书籍异常：${ex}")
            }
        }
    }
}


